<div class="app-content-body ">
  <div class="bg-light lter b-b wrapper-md hidden-print">
    <h1 class="m-n font-thin h3 main-title"></h1>
  </div>

  <div class="form_title">
    <div class="crud-container crud-reset">
      <form id="form-container">
        <div class="row">
          <div class="col-sm-12">
            <div id="dxtabs" style="margin-bottom: 30px"></div>
            <div id="wine-form">
              
            </div>
          </div>
        </div>
      </form>
      <div class="row">
        <div class="col-sm-12 text-right" style="margin-top: 15px;">
          <div id='saveData'></div>
          <div id="cancel"></div>
        </div>
      </div>
      
    </div>
  </div>
</div>
<script type="text/javascript">

  function validateForm(formInstance) {
    var editors = [];

    function _check(o) {
      if(o.dataField) {
        var editor = formInstance.getEditor(o.dataField);
        if(editor && typeof(editor.isExtInstance) === 'function') {
          editors.push(editor);
        }
      } else if(o.items) {
        $.each(o.items, function(i, item) {
          _check(item);
        })
      }
    }

    _check({
      items: formInstance.option('items')
    });

    var result = true;
    $.each(editors, function(i, e) {
      if(!e.validate()) result = false;
    });

    return result;
  }

  $(function() {
    $("#content").one("route.loaded", function(e, context) {
      var id = context.params.id, wineStore = $.crudStore(API("restful?_model=wine-product"));
      var formData = '', data = {};

      $(".main-title").text(id ? "编辑葡萄酒信息" : "新建葡萄酒信息");

      var xhrs = [], prefetchData = {}, formInstances = {};

      xhrs.push($.get(API("product-category")).then(function (resp) {
        prefetchData['product-category'] = resp.data;
      }));

      var dsSubdivision = new DevExpress.data.DataSource({
        store: $.crudStore(API('restful?_model=sys-subdivision'))
      });

      var dsRegion = new DevExpress.data.DataSource({
        store: $.crudStore(API('restful?_model=sys-region'))
      });

      var dsCountry = new DevExpress.data.DataSource({
        store: $.crudStore(API('restful?_model=sys-country'))
      });

      $.when.apply($, xhrs).then(function () {
        var formItems = {};

        formItems['drink'] = [{
          dataField: 'consume',
          label: { text: '消费指南' },
          editorType: 'dxTextArea'
        }, {
          itemType: 'group',
          colCount: '3',
          items: [{
              dataField: 'wineglass',
              label: { text: '杯形' }
            },
            {
              dataField: 'sober_time',
              label: { text:  '醒酒时间' }
            }, {
              dataField: 'temperature',
              label: { text:  '饮用温度' }
            }
          ]
        }, {
            itemType: 'group',
            items: [{
                dataField: 'chinese_food',
                label: { text:  '中餐搭配', }

              },
              {
                dataField: 'western_food',
                label: { text:  '西餐搭配' }
              }, {
                dataField: 'snack',
                label: { text:  '小食搭配' }
              },
              {
                dataField: 'undelicacy',
                label: { text:  '暗黑搭配' }
              }
            ]
        }, {

            dataField: 'talk_about',
            label: { text:  '谈资建议' },
            editorType: 'dxEditor'
        }];

        formItems['judge'] = [{
            dataField: 'letDrink_judge',
            label: { text:  '乐饮品鉴' },
            editorType: 'dxTextArea',
            editorOptions: {
              height: 200
            }
          },
          {
            dataField: 'judge_arr',
            label: { text:  '专家品鉴' },
            editorType: 'ExpertList'
          }
        ];

        formItems['score'] = [{
            dataField: 'self_arr',
            label: { text:  '本款酒' },
            editorType: "ExpertScoreList"
          }, {
            dataField: 'same_arr',
            label: { text:  '同系列酒' },
            editorType: "ExpertYearScoreList"
          }];

          formItems['technique'] = [{
              dataField: 'harvestDate',
              label: { text:  '采收时间' }
            }, {
              dataField: 'makeMethod',
              label: { text:  '酿造工艺' },
              editorType: 'dxTextArea'
            },
            {
              dataField: 'produceDate',
              label: { text:  '灌装时间' },
              editorType: 'YearSelect'
            },
            {
              dataField: 'yields',
              label: { text:  '产量' }
            }, {
              dataField: 'oakType',
              label: { text:  '橡木桶品牌' }
            }, {
              caption: "酿酒顾问",
              itemType: 'group',
              items: [{
                dataField: 'adviserName',
                label: { text:  '姓名' }
              }, {
                dataField: 'advisePicture',
                label: { text:  '头像' },
                editorType: 'ImageUploader',
                editorOptions: {
                  single: true,
                  imageWidth: 80,
                  imageHeight: 80
                }
              }, {
                dataField: 'adviserSummary',
                label: { text:  '简介' },
                editorType: 'dxTextArea',
                helpText: '300字左右'
              }]
            }, {
              caption:  "酿酒师",
              itemType: 'group',
              items: [{
                  dataField: 'makerName',
                  label: { text:  '名称' }
                },
                {
                  dataField: 'makerPicture',
                  label: { text:  '头像' },
                  editorType: 'ImageUploader',
                  editorOptions: {
                    single: true,
                    imageWidth: 80,
                    imageHeight: 80
                  }
                }, {
                  dataField: 'makerSummary',
                  label: { text:  '简介' },
                  editorType: 'dxTextArea',
                  helpText: '500字左右'
                }
              ]
            }
          ];

          formItems['degree'] = [{
              dataField: 'degree_score',
              label: { text:  '酒精度评分' },
              validationRules: [{
                type: "required",
                message: "请输入酒精度评分"
              }],
              editorType: "dxNumberBox",
              editorOptions: {
                max: 10,
                min: 0,
                placeholder: '0~10的整数'
              }
            },
            {
              dataField: 'sweetness',
              validationRules: [{
                type: "required",
                message: "请输入甜度"
              }],
              label: { text:  '甜度' },
              editorType: 'dxNumberBox',
              editorOptions: {
                max: 10,
                min: 0,
                placeholder: '0~10的整数'
              }
            }, {
              dataField: 'acidity',
              validationRules: [{
                type: "required",
                message: "请输入酸度"
              }],
              label: { text:  '酸度' },
              editorType: 'dxNumberBox',
              editorOptions: {
                max: 10,
                min: 0,
                placeholder: '0~10的整数'
              }
            }, {
              dataField: 'bitter',
              validationRules: [{
                type: "required",
                message: "请输入苦度"
              }],
              label: { text:  '苦度' },
              editorType: 'dxNumberBox',
              editorOptions: {
                max: 10,
                min: 0,
                placeholder: '0~10的整数'
              }
            }, {
              dataField: 'complexity',
              validationRules: [{
                type: "required",
                message: "请输入复杂度"
              }],
              label: { text:  '复杂度' },
              editorType: 'dxNumberBox',
              editorOptions: {
                max: 10,
                min: 0,
                placeholder: '0~10的整数'
              }
            }, {
              dataField: 'Intensity',
              validationRules: [{
                type: "required",
                message: "请输入浓郁度"
              }],
              label: { text:  '浓郁度' },
              editorType: 'dxNumberBox',
              editorOptions: {
                max: 10,
                min: 0,
                placeholder: '0~10的整数'
              }
            }, {
              dataField: 'aftertaste',
              validationRules: [{
                type: "required",
                message: "请输入回味"
              }],
              label: { text:  '回味' },
              editorType: 'dxNumberBox',
              editorOptions: {
                max: 10,
                min: 0,
                placeholder: '0~10的整数'
              }
            }, {
              dataField: 'wine_body',
              validationRules: [{
                type: "required",
                message: "请输入酒体"
              }],
              label: { text:  '酒体' },
              editorType: 'dxNumberBox',
              editorOptions: {
                max: 10,
                min: 0,
                placeholder: '0~10的整数'
              }
            }
          ];

          formItems['basic'] = [{
            itemType: 'group',
            colCount: 2,
            items: [{
              dataField: 'chateau_id',
              label: { text: '所属酒庄' },
              validationRules: [{type: "required"}],
              editorType: 'dxSelectBox',
              editorOptions: {
                dataSource: $.crudStore(API('restful?_model=wine-chateau')),
                showClearButton: true,
                placeholder: "酒庄",
                searchEnabled: true,
                valueExpr: 'id',
                noDataText: '没有请求到酒庄数据',
                itemTemplate: function(data, index, $el) {
                  if (data) {
                    $("<span>" + data.chname + " (" + data.name + ")</span>").appendTo($el);
                  }
                },
                displayExpr: function(data) {
                  return data ? data.chname + " (" + data.name + ")" : "";
                }
              },
              helpText: '葡萄酒所属的酒庄'

            }, {
              dataField: 'productCode',
              label: { text:  '葡萄酒编码' },
              helpText: '两位字母或者数字',
              validationRules: [{
                type: "required",
                message: "请输入葡萄酒编码"
              }],
              editorType: 'dxTextBox',
              editorOptions: {
                mask: 'AA'
              }
            }]
          }, {
              dataField: 'chname',
              validationRules: [{
                type: "required",
                message: "请输入中文名称"
              }],
              label: { text:  '中文名称' }
            }, {
              dataField: 'name',
              validationRules: [{
                type: "required",
                message: "请输入英文名称"
              }],
              label: { text:  '英文名称' }
            }, {
              dataField: 'letDrink_recom',
              validationRules: [{
                type: "required",
                message: "请输入乐饮推荐语"
              }, {
                type: "stringLength",
                min: 2,
                max: 10,
                message: "请输入至少2个，至多10个字符"
              }],
              label: { text:  '乐饮推荐语' },
              helpText: '请输入至少2个，至多10个字符'
            }, {
              itemType: 'group',
              colCount:3,
              items:[{
                dataField:'promotion_price',
                validationRules: [{type: "required"}],
              label: { text:  '促销价' },
              editorType: 'dxNumberBox'
              },{
              dataField: 'price',
              validationRules: [{type: "required"}],
              label: { text:  '原价' },
              editorType: 'dxNumberBox'
              },{
              dataField:'sku',
              label: { text:  '库存' },
              editorType: 'dxNumberBox'
              }]
             
            }, {
              dataField: 'banner',
              validationRules: [{
                type: "required"
              }],
              label: { text:  '封面图' },
              editorType: 'ImageUploader',
              editorOptions: {
                single: true,
                imageWidth: 750,
                imageHeight: 422
              }
            }, {
              dataField: 'covers',
              validationRules: [{
                type: "required"
              }],
              label: { text:  '轮播图' },
              editorType: 'ImageUploader',
              editorOptions: {
                imageWidth: 750,
                imageHeight: 1118
              }
            }, {
              itemType: 'group',
              colCount: 2,
              items: [{
                dataField: "country_id",
                label: { text:  '国家' },
                validationRules: [{type: "required"}],
                editorType: 'dxSelectBox',
                editorOptions: {
                  dataSource: dsCountry,
                  showClearButton: true,
                  placeholder: "国家",
                  searchEnabled: true,
                  searchExpr: ['chCountry', 'country'],
                  valueExpr: 'id',
                  noDataText: '没有请求到国家数据',
                  itemTemplate: function(data, index, $el) {
                    if (data) {
                      $("<span>" + data.chCountry + " (" + data.country + ")</span>").appendTo($el);
                    }
                  },
                  displayExpr: function(data) {
                    return data ? data.chCountry + " (" + data.country + ")" : "";
                  },
                  onValueChanged: function(e) {
                    dsRegion.filter('country_id', '=', e.value);
                    dsRegion.reload();
                  }
                }
              }, {
                dataField: 'subdivision_id',
                validationRules: [{ type: "required" }],
                label: { text: '地区(自动)' },
                editorType: 'dxSelectBox',
                editorOptions: {
                  readOnly: true,
                  dataSource: dsSubdivision,
                  showClearButton: true,
                  placeholder: "地区",
                  searchEnabled: true,
                  searchExpr: ['subdivision', 'subdivisionCode'],
                  valueExpr: 'id',
                  noDataText: '没有请求到地区数据',
                  itemTemplate: function(data, index, $el) {
                    if (data) {
                      $("<span>" + data.subdivision + " (" + data.subdivisionCode + ")</span>").appendTo($el);
                    }
                  },
                  displayExpr: function(data) {
                    return data ? data.subdivision + " (" + data.subdivisionCode + ")" : "";
                  }
                }
                
              }]
            }, {
              itemType: 'group',
              colCount: 2,
              items: [{
                dataField: 'region_id',
                validationRules: [{ type: "required" }],
                label: { text: '产区名称' },
                editorType: 'dxSelectBox',
                editorOptions: {
                  dataSource: dsRegion,
                  showClearButton: true,
                  placeholder: "产区名称",
                  searchEnabled: true,
                  searchExpr: ['chRegion', 'region'],
                  valueExpr: 'id',
                  noDataText: '没有请求到产区数据',
                  itemTemplate: function(data, index, $el) {
                    if (data) {
                      $("<span>" + data.chRegion + " (" + data.region + ")</span>").appendTo($el);
                    }
                  },
                  displayExpr: function(data) {
                    return data ? data.chRegion + " (" + data.region + ")" : "";
                  },
                  onSelectionChanged: function(e) {
                    formInstances['basic'].updateData({
                      regionCode: e.selectedItem ? e.selectedItem.regionCode : '',
                      subdivision_id: e.selectedItem ? e.selectedItem.subdivision_id : 0
                    });
                  }
                }
              }, {
                dataField: 'regionCode',
                label: { text: '产区编码(自动)' },
                editorType: 'dxTextBox',
                editorOptions: { readOnly: true }
              }]
            }, {
              itemType: 'group',
              colCount: '2',
              items: [{
                dataField: 'category',
                label: { text:  '类别' },
                validationRules: [{
                  type: "required",
                  message: "请输入类别"
                }],
                editorType: 'dxSelectBox',
                editorOptions: {
                  dataSource: prefetchData['product-category'],
                  acceptCustomValue: true,
                  onCustomItemCreating: function(e) {
                    return e.text;
                  },
                  placeholder: '选择或者输入类别'
                }
              }, {
                dataField: 'level',
                label: { text: '产品级别' }
              }]
            }, {
              dataField: 'win_info',
              label: { text: '获奖信息' }
            }, {
              dataField: 'deployment',
              label: { text: '调配类型' },
              validationRules: [{
                type: "required",
                message: "请输入调配类型"
              }],
              editorType: 'dxRadioGroup',
              editorOptions: {
                layout: "horizontal",
                valueExpr: 'value',
                dataSource: [{
                  text: '单一',
                  value: 'single'
                }, {
                  text: '混合',
                  value: 'blend'
                }],
                onValueChanged: function(e) {
                  var inst = formInstances["basic"].getEditor('deployment_graperies');

                  inst.option('mode', e.value);
                }
              }
            }, {
              dataField: 'deployment_graperies',
              label: { text: '葡萄种类' },
              editorType: 'GrapeDeployList',
              editorOptions: {
                mode: 'single'
              },
              validationRules: [{
                type: "required"
              }, {
                type: 'custom',
                validationCallback: function (params) {
                    $.ajax({
                        url: "http://www.example.com/services/validate-login",
                        method: "POST",
                        data: {
                            login: params.value
                        },
                        success: function (result) {
                            params.rule.isValid = result.Result;
                            params.rule.message = result.Message;
                            params.validator.validate();
                        }
                    })
                    // Validation result until the response is recieved
                    return false;
                }
              }]
            }, {
              itemType: 'group',
              colCount: '3',
              items: [{
                dataField: 'vintage',
                label: { text: '生产年份' },
                validationRules: [{
                  type: "required",
                  message: "请输入生产年份"
                }],
                editorType: 'YearSelect'
              }, {
                dataField: 'upTime',
                label: { text:  '最佳饮用时间' },
                validationRules: [{
                  type: "required",
                  message: "请输入最佳饮用时间"
                }],
                editorType: 'YearSelect'
              }, {
                dataField: 'unTime',
                validationRules: [{
                  type: "required",
                  message: "请输入不宜饮用时间"
                }],
                label: { text:  '不宜饮用时间' },
                editorType: 'YearSelect'
              }]
            }, {
              dataField: 'degree',
              label: { text:  '酒精度' },
              editorType: 'dxNumberBox',
              validationRules: [{
                type: "required",
                message: "请输入酒精度"
              }],
              editorOptions: {
                min: 1,
                max: 100,
                placeholder: '1~100'
              },

            }, {
              itemType: 'group',
              items: formItems['degree'],
              colCount: 4
            }, {
              dataField: 'scenes',
              label: { text:  '消费场景' },
              validationRules: [{
                type: "required",
                message: "请输入消费场景"
              }],
              editorType: 'dxTagBox',
              editorOptions: {
                dataSource: new DevExpress.data.DataSource({
                  store: $.crudStore(API("restful?_model=wine-scene")),
                  filter: ['parent_id', '>', 0],
                  paginate: false,
                  postProcess: function(data) {
                    var result = {};

                    $.each(data, function(i, d) {
                      if (result[d.parent_name]) {
                        result[d.parent_name].items.push(d);
                      } else {
                        result[d.parent_name] = {key: d.parent_name, items: []};
                      }
                    });

                    data = [];
                    for(var k in result) {
                      data.push(result[k]);
                    }

                    return data;
                  }
                }),
                valueExpr: 'id',
                displayExpr: 'name',
                acceptCustomValue: false,
                grouped: true,
                onValueChanged: function(e) {
                  if (e.value && e.value.length > 4) {
                    e.component.option('value', e.value.slice(0, 4));
                  }
                }
              }
            }, {
              dataField: 'relation_products',
              label: { text:  '关联葡萄酒' },
              editorType: 'dxTagBox',
              editorOptions: {
                deferRendering: false,
                dataSource: $.crudStore(API("restful?_model=wine-product")),
                searchEnabled: true,
                valueExpr: 'id',
                displayExpr: 'chname'
              }
            }
          ]

        var tabs = [{
          text: '基础信息',
          id: "basic"
        }, {
          text: "Drink介绍",
          id: "drink",
          disabled: ! id
        }, {
          text: "专业品鉴",
          id: "judge",
          disabled: ! id
        }, {
          text: "专业评分",
          id: "score",
          disabled: ! id
        }, {
          text: "技术信息",
          id: "technique",
          disabled: ! id
        }];

        $.each(["basic", "drink", "judge", "score", "technique"], function(index, item) {
          formInstances[item] = $("<div>").appendTo($("#wine-form")).dxForm({
            items: formItems[item],
            showColonAfterLabel: true,
            showValidationSummary: false,
            validationGroup: "crud",
            alignItemLabels: true,
            alignItemLabelsInAllGroups: true
          }).dxForm("instance");
        });

        function showTab(item) {
          for (var k in formInstances) {
            formInstances[k].option('visible', k === item);
          }
        }

        $("#dxtabs").dxTabs({
          dataSource: tabs,
          selectedIndex: 0,
          onItemClick: function(e) {
            showTab(e.itemData.id);
          }
        });

        showTab("basic");

        if(id) {
          wineStore.byKey(id).then(function (resp) {
            console.log(resp);

            $.each(["country_id", "chateau_id"], function(i, item) {
              resp[item] = parseInt(resp[item]);
            });

            $.each(["relation_products", "scenes"], function(i, item) {
              if (resp[item]) resp[item] = $.map(resp[item], function(it) { return it.id; });
            });

            var mapped = {
              blend_deployment: "deployment_graperies",
              "judge.expert_judges": "judge.judge_arr",
              "score.expert_scores": "score.self_arr",
              "score.same_scores": "score.same_arr"
            };

            for (var k in mapped) {
              if (_.has(resp, k)) {
                _.set(resp, mapped[k], _.get(resp, k));
                _.unset(resp, k);
              }
            }

            console.log(resp);

            var dataBasic = $.extend({}, resp);
            $.each(["drink", "score", "judge", "technique"], function(i, item) { 
              dataBasic[item] = undefined;
            });

            formInstances['basic'].option('formData', dataBasic);

            formInstances['drink'].option('formData', resp.drink);
            formInstances['judge'].option('formData', resp.judge);
            formInstances['technique'].option('formData', resp.technique);

            formInstances['score'].option('formData', resp.score);
            
          });

        } else {
          var productData = new DevExpress.data.CustomStore({
            store: $.crudStore(wineStore)
          });

          //form(productData)
        }
      });

      function saveCurrentTab() {
        var selectedItem = $("#dxtabs").dxTabs("option", "selectedItem");

        if (selectedItem) {
          $("#saveData").dxButton('option', { disabled: true, text: '正在保存' });

          var url = selectedItem.id === 'basic' ? API("restful?_model=wine-product") : API("restful?_model=wine-product-" + selectedItem.id);

          var formData = $.extend({}, formInstances[selectedItem.id].option('formData'));

          if (selectedItem.id !== 'basic') {
            formData.product_id = id;
          } else {
            var mapped = {
              relation_products: 'product_relation_ids',
              scenes: 'scene_ids'
            };

            for (var k in mapped) {
              if (formData[k]) {
                formData[mapped[k]] = formData[k].join(",");
              } else {
                formData[mapped[k]] = '';
              }

              formData[k] = undefined;
            }

            if (formData['covers']) {
              formData['cover_ids'] = $.map(formData['covers'], function(item) { return item.id; }).join(",");
            }
          }

          console.log(formData);

          var request = null;
          if (formData.id) {
            request = $.crudStore(url).update(formData.id, formData);
          } else {
            request = $.crudStore(url).insert(formData);
          }

          request.then(function(resp, data) {

            DevExpress.ui.notify({
              message: "已更新",
            }, "success", 1000);

            if (! id) {
              App.getEventContext().redirect('#/newproduct/' + data.data.id);
            }

            console.log(resp);
          }).fail(function (e) {

            var message = "更新失败";
            if ($.crudStoreResp && $.crudStoreResp.message) {
              message += ": " + $.crudStoreResp.message;
            }

            DevExpress.ui.notify({
              message: message,
            }, "error", 1000);

          }).always(function () {
            $("#saveData").dxButton('option', { disabled: false, text: '保存' });
          })
        }
      }

      $("#saveData").dxButton({
        text: id ? '保存' : '新建',
        type: 'success',
        useSubmitBehavior: false
      }).click(function () {
        var selectedItem = $("#dxtabs").dxTabs("option", "selectedItem");

        if (selectedItem) {
          var result = formInstances[selectedItem.id].validate();

          if (! result.isValid) {
            var $el = result.validators[0].element();

            var offset = $el.offset();

            $('html, body').animate({
                scrollTop: offset.top - $("header.app-header").height() - 20
            });

          } else if (validateForm(formInstances[selectedItem.id])) {
            saveCurrentTab();
          }
        }

        return false;
      })

      $("#cancel").dxButton({
        text: "返回",
        type: "normal",
        onClick: function() {
          context.redirect("#/members");
        }
      });
    });
  });
  console.log($.crudStore(API('restful?_model=sys-produce')))

</script>